package com.ruoyi.web.handle.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.web.domain.*;
import com.ruoyi.web.handle.service.GetOldDateService;
import com.ruoyi.web.mapper.*;
import com.ruoyi.web.util.TradingDays;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
@Service
public class GetOldDateServiceImpl implements GetOldDateService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private GuMrGuMapper guMrGuMapper;
    @Autowired
    private GuMrHszgMapper guMrHszgMapper;
    @Autowired
    private GuMrZtgcMapper guMrZtgcMapper;
    @Autowired
    private GuMrDtgcMapper guMrDtgcMapper;
    @Autowired
    private GuErrorLogMapper guErrorLogMapper;
    @Autowired
    private GuMrDapanMapper guMrDapanMapper;
    @Autowired
    private GuMrStockSnapshotMapper guMrStockSnapshotMapper;
    @Autowired
    private GuMrCompanyInfoMapper guMrCompanyInfoMapper;
    @Autowired
    private GuMrTradeDetailMapper guMrTradeDetailMapper;
    @Autowired
    private GuMrMoneyFlowFullMapper guMrMoneyFlowFullMapper;
    @Autowired
    private GuMrGuDapanMapper guMrGuDapanMapper;
    @Autowired
    private GuMrStockDailyMapper guMrStockDailyMapper;
    @Resource
    private SqlSessionFactory sqlSessionFactory;


    @Override
    public AjaxResult getJcDate() {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        //股票列表 http://api.mairuiapi.com/hslt/list/8D57E913-D7A4-4DE8-8E9D-522A095297ED
        //根据股票找相关指数、行业、概念 http://api.mairuiapi.com/hszg/zg/000001/8D57E913-D7A4-4DE8-8E9D-522A095297ED
        //获取每只股票名称及数据
        String url = "http://api.mairuiapi.com/hslt/list/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        Object obj = restTemplate.getForObject(url, Object.class, headers);
        //将object转换为string
        String userListString = JSON.toJSONString(obj);
        //将string封装为对象集合
        List<GuMrGu> guMrGuList = JSONObject.parseArray(userListString,GuMrGu.class);
        if(guMrGuList!=null&&guMrGuList.size()>0){
            guMrGuMapper.truncateTable();
        }
        for (GuMrGu guMrGu : guMrGuList) {
            guMrGu.setId(guMrGu.getDm());
            //根据股票找相关的指数行业
            String code = guMrGu.getDm().replaceAll("[.]|[a-zA-Z]", "");
            String url2 = "http://api.mairuiapi.com/hszg/zg/"+code+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            logger.info("【获取股票相关行业】---{}",JSON.toJSONString(guMrGu));
            try{
                Object obj2 = restTemplate.getForObject(url2, Object.class, headers);
                //将object转换为string

                String ListString2 = JSON.toJSONString(obj2);

                //将string封装为对象集合
                List<GuMrHszg> guMrHszgsList = JSONObject.parseArray(ListString2,GuMrHszg.class);

                String gn1 = "";
                String gn2 = "";
                for(GuMrHszg guMrHszg : guMrHszgsList){
                    if(gn1.isEmpty()){
                        gn1 = guMrHszg.getCode();
                    } else  {
                        gn1 = gn1+","+guMrHszg.getCode();
                    }
                    if(gn2.isEmpty()){
                        gn2 = guMrHszg.getCode();
                    }else   {
                        gn2 = gn2+","+guMrHszg.getCode();
                    }
                }
                guMrGu.setGn1(gn1);
                guMrGu.setGn2(gn2);
                guMrGu.setCreateTime(DateUtils.getNowDate());
                guMrGuMapper.insertGuMrGu(guMrGu);
            }catch (Exception e){
                logger.error("【获取股票相关行业接口获取出错】---{}",JSON.toJSONString(guMrGu));
                GuErrorLog guErrorLog = new GuErrorLog();
                guErrorLog.setId(UUID.randomUUID().toString().replace("-",""));
                guErrorLog.setCreateTime(DateUtils.getNowDate());
                guErrorLog.setRemark("【获取股票相关行业接口获取出错】---"+JSON.toJSONString(guMrGu));
                guErrorLogMapper.insertGuErrorLog(guErrorLog);
            }

        }

        return AjaxResult.success();
    }

    @Override
    public AjaxResult getHy() {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        //指数、行业、概念树 http://api.mairuiapi.com/hszg/list/8D57E913-D7A4-4DE8-8E9D-522A095297ED
        String url1 = "http://api.mairuiapi.com/hszg/list/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
        Object obj1 = restTemplate.getForObject(url1, Object.class, headers);
        String ListString3 = JSON.toJSONString(obj1);
        //将string封装为对象集合
        List<GuMrHszg> gumerHszgList = JSONObject.parseArray(ListString3,GuMrHszg.class);
        for( GuMrHszg  guMrHszg : gumerHszgList){
            guMrHszg.setId(UUID.randomUUID().toString().replace("-",""));
            guMrHszgMapper.insertGuMrHszg(guMrHszg);
        }
        return null;
    }

    @Override
    public AjaxResult getZs() {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        //沪深主要指数列表接口 http://api.mairuiapi.com/hsindex/list/8D57E913-D7A4-4DE8-8E9D-522A095297ED
        String url2 ="http://api.mairuiapi.com/hsindex/list/8D57E913-D7A4-4DE8-8E9D-522A095297ED" ;
        Object object = restTemplate.getForObject(url2, Object.class, headers);
        String ob1 = JSON.toJSONString(object);
        List<GuMrGuDapan> guMrGuDapans = JSONObject.parseArray(ob1,GuMrGuDapan.class);
        for(GuMrGuDapan guMrGuDapan : guMrGuDapans) {
            guMrGuDapan.setCreateTime(DateUtils.getNowDate());
            guMrGuDapan.setId(UUID.randomUUID().toString().replace("-",""));
            guMrGuDapanMapper.insertGuMrGuDapan(guMrGuDapan);
        }
        return null;
    }

    @Async
    @Override
    public AjaxResult getZjlxDate(String code) {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        //【资金流向数据】 http://api.mairuiapi.com/hsstock/history/transaction/000001/8D57E913-D7A4-4DE8-8E9D-522A095297ED
        try {
            String url ="http://api.mairuiapi.com/hsstock/history/transaction/"+code+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
            Object object = restTemplate.getForObject(url, Object.class, headers);
            List<GuMrMoneyFlowFull> guMrMoneyFlowFulls = JSONObject.parseArray(JSON.toJSONString(object), GuMrMoneyFlowFull.class);
            for (GuMrMoneyFlowFull guMrMoneyFlowFull : guMrMoneyFlowFulls){
                guMrMoneyFlowFull.setCreateTime(DateUtils.getNowDate());
                guMrMoneyFlowFull.setCode(code);
                guMrMoneyFlowFull.setId(UUID.randomUUID().toString().replace("-",""));
                guMrMoneyFlowFullMapper.insertGuMrMoneyFlowFull(guMrMoneyFlowFull);
            }
        } catch (RestClientException e) {
            GuErrorLog guErrorLog = new GuErrorLog();
            guErrorLog.setId(UUID.randomUUID().toString().replace("-",""));
            guErrorLog.setCreateTime(DateUtils.getNowDate());
            guErrorLog.setRemark("【获取股票资金流入接口获取出错】---"+code);
            guErrorLogMapper.insertGuErrorLog(guErrorLog);
        }
        return null;
    }


    @Async
    @Override
    public AjaxResult getFsDate(String code ,String mc) {
        // 关闭session的自动提交
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);


        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        //【历史分时交易】：https://api.mairuiapi.com/hsstock/history/000001.SZ/d/n/8D57E913-D7A4-4DE8-8E9D-522A095297ED?st=20250101&et=20250430&lt=100
        //  不设置开始时间和结束时间则为全部历史数据。

        try {
            //8D57E913-D7A4-4DE8-8E9D-522A095297ED
            String url = "https://api.mairuiapi.com/hsstock/history/"+code+"/d/n/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
            Object object2 = restTemplate.getForObject(url, Object.class, headers);
            String ob2 = JSON.toJSONString(object2);
            List<GuMrStockDaily> guMrStockDailies = JSONObject.parseArray(ob2,GuMrStockDaily.class);
            for(GuMrStockDaily  guMrStockDaily : guMrStockDailies){
                guMrStockDaily.setId(UUID.randomUUID().toString().replace("-",""));
                guMrStockDaily.setCreateTime(DateUtils.getNowDate());
                guMrStockDaily.setCode(code);
                guMrStockDaily.setRemark(mc);
                //guMrStockDailyMapper.insertGuMrStockDaily(guMrStockDaily);
                logger.info("不插入循环展示--{}",JSON.toJSONString(guMrStockDaily));
            }
            try {
                logger.info("ZHIXING+++++++++++++++++++++");
                GuMrStockDailyMapper guMrStockDailyMapper = sqlSession.getMapper(GuMrStockDailyMapper.class);
                guMrStockDailies.stream().forEach(guMrStockDaily -> guMrStockDailyMapper.insertGuMrStockDaily(guMrStockDaily));
                // 提交数据
                sqlSession.commit();
            } catch (Exception e) {
                sqlSession.rollback();
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            GuErrorLog guErrorLog = new GuErrorLog();
            guErrorLog.setId(UUID.randomUUID().toString().replace("-",""));
            guErrorLog.setCreateTime(DateUtils.getNowDate());
            guErrorLog.setRemark(e.getMessage()+"=个股历史交易="+code);
            guErrorLogMapper.insertGuErrorLog(guErrorLog);

        }
        return null;
    }

    @Async
    @Override
    public AjaxResult getTestOne() {

        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        //【历史分时交易】：https://api.mairuiapi.com/hsstock/history/000001.SZ/d/n/8D57E913-D7A4-4DE8-8E9D-522A095297ED?st=20250101&et=20250430&lt=100
        //  不设置开始时间和结束时间则为全部历史数据。

        try {
            //8D57E913-D7A4-4DE8-8E9D-522A095297ED
            String url = "https://api.mairuiapi.com/hsstock/history/000001.SZ/d/n/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
            Object object2 = restTemplate.getForObject(url, Object.class, headers);
            String ob2 = JSON.toJSONString(object2);
            List<GuMrStockDaily> guMrStockDailies = JSONObject.parseArray(ob2,GuMrStockDaily.class);
            for(GuMrStockDaily  guMrStockDaily : guMrStockDailies){
                guMrStockDaily.setId(UUID.randomUUID().toString().replace("-",""));
                guMrStockDaily.setCreateTime(DateUtils.getNowDate());
                guMrStockDaily.setCode("000001.SZ");
                guMrStockDaily.setRemark("平安银行");
                guMrStockDailyMapper.insertGuMrStockDaily(guMrStockDaily);
            }
        } catch (Exception e) {
            GuErrorLog guErrorLog = new GuErrorLog();
            guErrorLog.setId(UUID.randomUUID().toString().replace("-",""));
            guErrorLog.setCreateTime(DateUtils.getNowDate());
            guErrorLog.setRemark(e.getMessage()+"=个股历史交易=getTestOne");
            guErrorLogMapper.insertGuErrorLog(guErrorLog);

        }
        return null;
    }

    @Override
    public AjaxResult getDtZtDate() {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        // 【获取涨停 跌停 历史数据】
        // [涨停]http://api.mairuiapi.com/hslt/ztgc/2024-01-10/8D57E913-D7A4-4DE8-8E9D-522A095297ED
        //【跌停】http://api.mairuiapi.com/hslt/dtgc/2024-01-10/8D57E913-D7A4-4DE8-8E9D-522A095297ED

        List<String> stringList = TradingDays.getTradingDays();
        for(int i =0 ;i<stringList.size() ; i++){
            List<GuMrZtgc> mrZtgcs = null;
            List<GuMrDtgc>  dtgcs  = null;
            try {
                //String formattedDate = date.format(formatter);

                String url2 ="http://api.mairuiapi.com/hslt/ztgc/"+stringList.get(i)+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
                String url3 ="http://api.mairuiapi.com/hslt/dtgc/"+stringList.get(i)+"/8D57E913-D7A4-4DE8-8E9D-522A095297ED";
                Object object3 = restTemplate.getForObject(url2, Object.class, headers);
                Object object4 = restTemplate.getForObject(url3, Object.class, headers);
                String ob3 = JSON.toJSONString(object3);
                String ob4 = JSON.toJSONString(object4);
                mrZtgcs = JSONObject.parseArray(ob3, GuMrZtgc.class);
                dtgcs = JSONObject.parseArray(ob4, GuMrDtgc.class);
                for(GuMrZtgc guMrZtgc : mrZtgcs){
                    guMrZtgc.setId(UUID.randomUUID().toString().replace("-",""));
                    guMrZtgc.setCreateTime(DateUtils.getNowDate());
                    guMrZtgcMapper.insertGuMrZtgc(guMrZtgc);
                }
                for(GuMrDtgc guMrDtgc : dtgcs){
                    guMrDtgc.setId(UUID.randomUUID().toString().replace("-",""));
                    guMrDtgc.setCreateTime(DateUtils.getNowDate());
                    guMrDtgcMapper.insertGuMrDtgc(guMrDtgc);
                }
            } catch (RestClientException e) {
                GuErrorLog guErrorLog = new GuErrorLog();
                guErrorLog.setId(UUID.randomUUID().toString().replace("-",""));
                guErrorLog.setCreateTime(DateUtils.getNowDate());
                guErrorLog.setRemark(e.getMessage()+"获取历史涨跌停出错=="+stringList.get(i));
                guErrorLogMapper.insertGuErrorLog(guErrorLog);
            }


        }


        return null;
    }

    @Async
    @Override
    public AjaxResult getDaPanDate(String code,String mc) {
        RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-Type", "application/json;charset=UTF-8");
        //【历史分时交易】 http://api.mairuiapi.com/hsindex/history/000001.SZ/d/8D57E913-D7A4-4DE8-8E9D-522A095297ED?st=20250101&et=20250430
        try {
            //8D57E913-D7A4-4DE8-8E9D-522A095297ED
            String url2 = "http://api.mairuiapi.com/hsindex/history/"+code+"/d/8D57E913-D7A4-4DE8-8E9D-522A095297ED" ;
            Object object2 = restTemplate.getForObject(url2, Object.class, headers);
            String ob2 = JSON.toJSONString(object2);
            List<GuMrDapan> guMrDapans = JSONObject.parseArray(ob2,GuMrDapan.class);
            for(GuMrDapan  guMrDapan : guMrDapans){
                guMrDapan.setId(UUID.randomUUID().toString().replace("-",""));
                guMrDapan.setCreateTime(DateUtils.getNowDate());
                guMrDapan.setZscode(code);
                guMrDapan.setRemark(mc);
                guMrDapanMapper.insertGuMrDapan(guMrDapan);
            }
        } catch (Exception e) {
            GuErrorLog guErrorLog = new GuErrorLog();
            guErrorLog.setId(UUID.randomUUID().toString().replace("-",""));
            guErrorLog.setCreateTime(DateUtils.getNowDate());
            guErrorLog.setRemark(e.getMessage()+"=获取大盘历史数据出错="+code);
            guErrorLogMapper.insertGuErrorLog(guErrorLog);

        }
        return null;
    }
}
